import React, { useState, useEffect } from 'react';
import { Card, Form, Row, Col, Button, Table, DatePicker } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import { withRouter } from 'react-router-dom';
import { useSyncCallback, deepclone } from '@/utils';
import moment from 'moment';
import './index.scss';
import { 
  merchantOutlinePage
} from '@/api/report'

let first = false
let orCToken = {}
const MerchantSummary = (props) => {
  const [searchForm] = Form.useForm();
  const { RangePicker } = DatePicker;
  // 筛选数据
  const [values] = useState({
    "time": [moment(),moment()],
  })
  // 分页
  const [dataSource, setDataSource] = useState([]);
  // 面包屑
  const breadcrumbList = ['报表管理', '新商户概要统计']
  // 布局
  const layout1 = { sm: 24, md: 12, lg: 12, xl: 6, xxl: 6 };
  const labelCol = { sm: 24, md: 8, lg: 8, xl: 8 };
  const wrapperCol = { sm: 24, md: 16, lg: 16, xl: 16 };
  
  const [formData, setFormData] = useState(values)
  let [loading, setLoading] = useState(false)
  // 表单头部
  const columns = [
    {
      title: '日期',
      dataIndex: 'countDate',
      key: 'countDate',
      align: 'center',
    },
    {
      title: '商户充值人数',
      children: [
        {
          title: '总计',
          dataIndex: 'merchantRechargeTotalPens',
          key: 'merchantRechargeTotalPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.getDetail(item,0,1)}}>{text}</a>
          // ),
        },
        {
          title: '新会员',
          dataIndex: 'merchantRechargeNewPens',
          key: 'merchantRechargeNewPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.getDetail(item,0,2)}}>{text}</a>
          // ),
        },
        {
          title: '老会员',
          dataIndex: 'merchantRechargeOldPens',
          key: 'merchantRechargeOldPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.getDetail(item,0,3)}}>{text}</a>
          // ),
        },
      ]
    },
    {
      title: '商户转账人数',
      children: [
        {
          title: '总计',
          dataIndex: 'merchantTransferTotalPens',
          key: 'merchantTransferTotalPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.showModal(item.countDate,3,3)}}>{text}</a>
          // ),
        },
        {
          title: '新会员',
          dataIndex: 'merchantTransferNewPens',
          key: 'merchantTransferNewPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.showModal(item.countDate,3,1)}}>{text}</a>
          // ),
        },
        {
          title: '老会员',
          dataIndex: 'merchantTransferOldPens',
          key: 'merchantTransferOldPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.showModal(item.countDate,3,2)}}>{text}</a>
          // ),
        },
      ]
    },
    {
      title: '商户提现人数',
      children: [
        {
          title: '总计',
          dataIndex: 'merchantWithdrawTotalPens',
          key: 'merchantWithdrawTotalPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.getDetail(item,1,1)}}>{text}</a>
          // ),
        },
        {
          title: '新会员',
          dataIndex: 'merchantWithdrawNewPens',
          key: 'merchantWithdrawNewPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.getDetail(item,1,2)}}>{text}</a>
          // ),
        },
        {
          title: '老会员',
          dataIndex: 'merchantWithdrawOldPens',
          key: 'merchantWithdrawOldPens',
          align: 'center',
          // render: (text: any, item: any) => (
          //   <a onClick={()=>{this.getDetail(item,1,3)}}>{text}</a>
          // ),
        },
      ]
    },
  ];
  const addAct = (aValue=0,bValue=0) => {
    let sum = 0;
    aValue = aValue.toString()
    bValue = bValue.toString()
    let aLength = aValue.indexOf('.') !== -1 ? aValue.split('.')[1].length : 0;
    let bLength = bValue.indexOf('.') !== -1 ? bValue.split('.')[1].length : 0;
    if(aLength > bLength){
      sum = (parseFloat(aValue) + parseFloat(bValue)).toFixed(aLength)
      console.log(aLength)
    }else{
      sum = (parseFloat(aValue) + parseFloat(bValue)).toFixed(bLength)
    }
    return sum;
  };
  // 提交弹框表单做防抖处理
  const onFinish = async () => {
    let values = deepclone(formData)
    try {
      let params = {
         startDate: moment(values.time[0]).format('YYYY-MM-DD'),
         endDate: moment(values.time[1]).format('YYYY-MM-DD'),
       }
      setLoading(true)
      let res = await merchantOutlinePage(params, orCToken)
      if(res.code === 0) {
        if(res.data&&res.data.records){
          let merchantOutlineTotal = {
            countDate: '',
            merchantRechargeNewPens: 0,
            merchantRechargeOldPens: 0,
            merchantRechargeTotalPens: 0,
            merchantTransferNewPens: 0,
            merchantTransferOldPens: 0,
            merchantTransferTotalPens: 0,
            merchantWithdrawNewPens: 0,
            merchantWithdrawOldPens: 0,
            merchantWithdrawTotalPens: 0
          };
          for (let i = 0; i < res.data.records.length; i++) {
            merchantOutlineTotal.countDate = '总计:' + res.data.records.length + '行';
            merchantOutlineTotal.merchantRechargeNewPens = addAct(merchantOutlineTotal.merchantRechargeNewPens,res.data.records[i].merchantRechargeNewPens);
            merchantOutlineTotal.merchantRechargeOldPens = addAct(merchantOutlineTotal.merchantRechargeOldPens,res.data.records[i].merchantRechargeOldPens);
            merchantOutlineTotal.merchantRechargeTotalPens = addAct(merchantOutlineTotal.merchantRechargeTotalPens,res.data.records[i].merchantRechargeTotalPens);
            merchantOutlineTotal.merchantTransferNewPens = addAct(merchantOutlineTotal.merchantTransferNewPens,res.data.records[i].merchantTransferNewPens);
            merchantOutlineTotal.merchantTransferOldPens = addAct(merchantOutlineTotal.merchantTransferOldPens,res.data.records[i].merchantTransferOldPens);
            merchantOutlineTotal.merchantTransferTotalPens = addAct(merchantOutlineTotal.merchantTransferTotalPens,res.data.records[i].merchantTransferTotalPens);
            merchantOutlineTotal.merchantWithdrawNewPens = addAct(merchantOutlineTotal.merchantWithdrawNewPens,res.data.records[i].merchantWithdrawNewPens);
            merchantOutlineTotal.merchantWithdrawOldPens = addAct(merchantOutlineTotal.merchantWithdrawOldPens,res.data.records[i].merchantWithdrawOldPens);
            merchantOutlineTotal.merchantWithdrawTotalPens = addAct(merchantOutlineTotal.merchantWithdrawTotalPens,res.data.records[i].merchantWithdrawTotalPens);
          }
          setDataSource([...res.data.records, merchantOutlineTotal])
        }else{
          setDataSource([])
        }
      }else{
        setDataSource([])
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  };
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    onFinish()
  })
  //改变搜索条件更新
  useEffect(() => {
    if(first) {
      // searchData()
    }
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  // 首次更新
  useEffect(() => {
    searchData()
    first = true
    return () => { 
      first = false
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  
  // 初始化
  return (
  <div>
    <div>
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className='agent-main'>
        <Form
          initialValues={values} 
          form={searchForm} 
          onFinish={(val) => {
            setFormData(val)
            searchData()
          }}>
          <Card className="formCard" style={{ width: '100%' }} bordered={false}>
            <Row>
              <Col {...layout1}>
                <Form.Item
                  name="time"
                  className="formItem"
                  label="日期范围"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <RangePicker allowClear={false} />
                </Form.Item>
              </Col>
              <Col {...layout1}>
                <span className="buttonLeft">
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                  <Button
                    className="reset-btn"
                    type="default"
                    onClick={() => {
                      searchForm.resetFields()
                    }}
                  >
                    重置
                  </Button>
                </span>
              </Col>
            </Row>
          </Card>
        </Form>
        <div className='table-box'>
          <Card>
            <div className='table'>
              <Table
                loading={loading}
                size='middle'
                bordered
                scroll={{ x: 1224 }}
                rowKey={() => {return Math.floor(Math.random() * 100000000000)+''}}
                className='antd-table'
                dataSource={dataSource}
                columns={columns} />
            </div>
          </Card>
        </div>
      </div>
    </div>
  </div>
  )
}
export default withRouter(MerchantSummary)